package com.taa.controller;

import com.taa.entity.Cart;
import com.taa.entity.User;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: taa
 * @Desc: 消费端控制层
 * @Create: 2025-06-14 15:38
 **/
@RestController
@RequestMapping("/consumer")
public class CartConsumerController {

    @Resource
    private DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate = new RestTemplate();
    
    @GetMapping("/cart/{userId}")
    public Cart getCart(@PathVariable("userId") Long userId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        if (instances.isEmpty()) {
            throw new RuntimeException("No provider-service available!");
        }

        String providerUrl = instances.get(0).getUri() + "/provider/cart/" + userId;
        return restTemplate.getForObject(providerUrl, Cart.class);
    }
}

